<?php
namespace addons\wxlogin\library;

use hema\Http;

/**
 * 微信登录接口类
 **/
class Wxlogin
{
    private $api_url = 'https://api.weixin.qq.com';
    private $config;
    private $error;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->config = get_addons_config('wxlogin');
        
    }
    
    
    /**
     * code换取token
     */
    function getToken(string $code)
    {
        $url = $this->getUrl('oauth2/access_token');
        $queryarr = [
            'appid' => $this->config['app_id'],
            'secret' => $this->config['app_secret'],
            'grant_type' => 'authorization_code',
            'code' => $code
        ];
        $result = json_decode(Http::get($url,$queryarr),true);
        if(!isset($result['access_token'])){
            $this->error = '获取access_token失败';
	    	return false;
	    }
	    $result['user_model'] = $this->config['user_model'];//用户表模型
	    $result['redirect_uri'] = $this->config['redirect_uri'];//跳转位置
        return $result;
    }
    
    /**
     * 组合接口地址
     **/
    private function getUrl($url)
    {
        return $this->api_url . '/sns/' . $url;
    }
    
    public function getError()
    {
        return $this->error;
    }

}
